//
//  NEDSheetView.m
//  MoreCoin
//
//  Created by 林宁宁 on 2019/9/23.
//  Copyright © 2019 MoreCoin. All rights reserved.
//

#import "NEDSheetView.h"
#import "UIButton+NED.h"
#import "NEDTableViewCell.h"
#import "UIColor+NEDStyle.h"
#import "UIFont+NED.h"
#import "NEDDefines.h"
#import "NEDConstant.h"
#import "UIView+NED.h"
#import "NEDDeviceInfo.h"


@interface NEDSheetOptionCell : NEDTableViewCell

@property (retain, nonatomic) UILabel * cellTitle;

@end


@implementation NEDSheetOptionCell

-(void)ned_commonInit{
    
    self.contentView.backgroundColor = [UIColor ned_background];
    self.backgroundColor = [UIColor ned_background];
    
    self.cellTitle = [UILabel new];
    self.cellTitle.backgroundColor = [UIColor clearColor];
    self.cellTitle.numberOfLines = 0;
    [self.contentView addSubview:self.cellTitle];
    [self.cellTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
}

@end




@implementation NEDSheetItem

-(instancetype)init{
    self = [super init];
    if(self){
        self.alignment = NSTextAlignmentCenter;
    }
    return self;
}

-(void)setTitle:(NSString *)title{
    _title = title;
    [self updateStyle];
}

-(void)setOptionType:(NEDSheetOptionType)optionType{
    _optionType = optionType;
    [self updateStyle];
}

-(void)setTitleColor:(UIColor *)titleColor{
    _titleColor = titleColor;
    [self updateStyle];
}

- (void)updateStyle{
    if(self.title){
        self.titleAtt = [NSMutableAttributedString ned_initWithStr:self.title customBlock:^(NSMutableAttributedString *att) {
            [att ned_font:[UIFont ned_pfOfSize:18]];
            [att ned_color:[UIColor ned_h1]];
        }];
    }
    if(self.titleColor && self.title){
        [self.titleAtt ned_color:self.titleColor range:[self.titleAtt.string rangeOfString:self.title]];
    }
    [self.titleAtt ned_paragraphBlock:^(NSMutableParagraphStyle *style) {
        style.alignment = self.alignment;
    }];
}

@end





CGFloat const NEDSheetHeightCell = 60;
CGFloat const NEDSheetHeightSpaceSection = 10;


@interface NEDSheetView()<UITableViewDelegate,UITableViewDataSource>

@property (retain, nonatomic) NSMutableArray <NEDSheetItem *>* dataList;
@property (retain, nonatomic) NEDSheetItem * cancelItem;
@property (retain, nonatomic) NEDSheetItem * titleItem;

@property (retain, nonatomic) UITableView * tableV;

@end

@implementation NEDSheetView



- (void)ned_setupUI{
    
    WS(weakSelf)
    
    self.dataList = [NSMutableArray new];
    
    self.contentView.layer.cornerRadius = 0;
    self.contentView.layer.masksToBounds = NO;
    self.contentView.backgroundColor = [UIColor ned_background];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(weakSelf);
        make.height.mas_equalTo([NEDDeviceInfo height_home_indicator] + 200);
    }];
    
    self.tableV = [UITableView new];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    self.tableV.rowHeight = NEDSheetHeightCell;
    self.tableV.backgroundColor = [UIColor clearColor];
    self.tableV.separatorColor = [UIColor ned_separator];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000
    if (@available(iOS 15.0, *)) {
        self.tableV.sectionHeaderTopPadding = 0;
    }
#endif
    [self.contentView addSubview:self.tableV];
    [self.tableV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
    [self.tableV registerClass:[NEDSheetOptionCell class] forCellReuseIdentifier:[NEDSheetOptionCell cellIndentify]];
    
    self.backgroundView.backgroundColor = [[UIColor ned_black] colorWithAlphaComponent:0.1];
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    [self.backgroundView addGestureRecognizer:pan];
}
 
-(void)ned_setupData{
    NSInteger contentHeight = 0;
    if(self.titleItem){
        contentHeight = contentHeight + self.titleItem.cellHeight>0?self.titleItem.cellHeight:NEDSheetHeightCell;
    }
    contentHeight = contentHeight + NEDSheetHeightCell*self.dataList.count;
    if(self.cancelItem){
        contentHeight = contentHeight + NEDSheetHeightCell + NEDSheetHeightSpaceSection;
    }
    contentHeight = contentHeight + [NEDDeviceInfo height_home_indicator];
    contentHeight = MIN([NEDDeviceInfo s_height]*0.7, contentHeight);
    self.tableV.bounces = contentHeight > [NEDDeviceInfo s_height]*0.7;
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(contentHeight);
    }];
}


-(void)ned_popShowAnimation{
    [self.contentView cornerTop:20];
    
    self.contentView.transform = CGAffineTransformMakeTranslation(0, 200);
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.contentView.transform = CGAffineTransformIdentity;    
    } completion:^(BOOL finished) {
        
    }];
}

- (void)panGesture:(UIPanGestureRecognizer *)sender{
    if(sender.state == UIGestureRecognizerStateChanged ||
       sender.state == UIGestureRecognizerStateEnded){
        
        CGPoint offset = [sender translationInView:self.backgroundView];
        
        if(sender.state == UIGestureRecognizerStateChanged){
            if(offset.y > 0){
                self.contentView.transform = CGAffineTransformMakeTranslation(0, offset.y);
            }
        }else{
            CGFloat velocity = [sender velocityInView:self.backgroundView].y;
            
            if(offset.y > CGRectGetHeight(self.contentView.frame)*0.5 ||
               (velocity > 300 && offset.y > 20) ){
                // 超过一半 要自动移出去
                [UIView animateWithDuration:0.2 animations:^{
                    self.alpha = 0;
                    self.contentView.transform = CGAffineTransformMakeTranslation(0, CGRectGetHeight(self.contentView.frame)*1.5);
                } completion:^(BOOL finished) {
                    if(finished){
                        [self removeFromSuperview];
                    }
                    if(self.didCloseBlock){
                        self.didCloseBlock();
                    }
                }];
            }else{
                //恢复 过段时间再消失
                [UIView animateWithDuration:0.2 animations:^{
                    self.contentView.transform = CGAffineTransformIdentity;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }
    }
}

#pragma mark - delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        if(self.titleItem) return 1;
        return 0;
    }else if (section == 1){
        return self.dataList.count;
    }else if(section == 2){
        if(self.cancelItem) return 1;
        return 0;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NEDSheetOptionCell * cell = [tableView dequeueReusableCellWithIdentifier:[NEDSheetOptionCell cellIndentify]];
    if(indexPath.section == 0){
        cell.cellTitle.attributedText = self.titleItem.titleAtt;
        self.tableV.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);

    }else if (indexPath.section == 1){
        NEDSheetItem * item = self.dataList[indexPath.row];
        cell.cellTitle.attributedText = item.titleAtt;
    }else if(indexPath.section == 2){
        cell.cellTitle.attributedText = self.cancelItem.titleAtt;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)  return;
    if (indexPath.section == 1){
        NEDSheetItem * item = self.dataList[indexPath.row];
        if(item.clickBlock){
            item.clickBlock(self);
        }
    }
    [self popDismiss];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }else{
        [cell setSeparatorInset:UIEdgeInsetsMake(0, [NEDDeviceInfo s_width], 0, 0)];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
     
    if(section == 0){
        return 0;
    }else if (section == 1){
        return 0;
    }else if(section == 2){
        if(self.cancelItem) return NEDSheetHeightSpaceSection;
        return 0;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && self.titleItem) {
        if (self.titleItem.cellHeight > 0) {
            return self.titleItem.cellHeight;
        }
    }
    return NEDSheetHeightCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * v = [UIView new];
    v.backgroundColor = [UIColor ned_separator].ned_alpha(0.2);
    return v;
}

#pragma mark -


-(void)addOptionTitle:(NSString *)title action:(void (^)(NEDSheetView * _Nonnull))action{
    [self addOptionBlock:^(NEDSheetItem * _Nonnull passItem) {
        passItem.title = title;
    } action:action];
}
- (void)addOptionRedTitle:(NSString *)title action:(void(^ _Nullable)(NEDSheetView * alertV))action{
    [self addOptionBlock:^(NEDSheetItem * _Nonnull passItem) {
        passItem.title = title;
        passItem.titleColor = [UIColor ned_red];
    } action:action];
}

- (void)addOptionTitle:(NSString *)title titleColor:(UIColor *)titleColor action:(void(^ _Nullable)(NEDSheetView * alertV))action{
    [self addOptionBlock:^(NEDSheetItem * _Nonnull passItem) {
        passItem.title = title;
        passItem.titleColor = titleColor;
    } action:action];
}

-(void)addOptionBlock:(void (^)(NEDSheetItem * _Nonnull))callBlock action:(void (^)(NEDSheetView * _Nonnull))action{
    
    NEDSheetItem * item = [NEDSheetItem new];
    item.optionType = NEDSheetOptionType_Normal;
    item.clickBlock = action;
    if(callBlock){
        callBlock(item);
    }
    [self.dataList addObject:item];
}

- (void)addCancel{
    [self addCancelTitle:@"取消"];
}
- (void)addCancelTitle:(NSString *)title{
    [self addCancelBlock:^(NEDSheetItem * _Nonnull passItem) {
        passItem.title = title;
    } action:nil];
}
- (void)addCancelBlock:(void (^)(NEDSheetItem * _Nonnull))callBlock action:(void (^)(NEDSheetView * _Nonnull))action{
    if(!self.cancelItem){
        self.cancelItem = [NEDSheetItem new];
        self.cancelItem.optionType = NEDSheetOptionType_Cancel;
    }
    if(callBlock){
        callBlock(self.cancelItem);
    }
    self.cancelItem.clickBlock = action;
}

- (void)addHeadTitle:(NSString *)title{
    [self addHeadTitle:title description:nil];
}
- (void)addHeadTitle:(NSString * _Nullable)title description:(NSString * _Nullable)description{
    if(IsNull(title) && IsNull(description)){
        return;
    }
    if(IsNonNull(title) && IsNonNull(description)){
        [self addHeadTitleBlock:^(NEDSheetItem * _Nonnull passItem) {
            NSMutableAttributedString * att = [NSMutableAttributedString ned_initWithStr:title customBlock:^(NSMutableAttributedString *att) {
                [att ned_font:[UIFont ned_pfmOfSize:16]];
                [att ned_color:[UIColor ned_h1]];
            }];
            [att ned_appendStr:@"\n" block:nil];
            [att ned_appendStr:description block:^(NSMutableAttributedString *attStr, NSString *str) {
                [attStr ned_font:[UIFont ned_pfOfSize:12]];
                [attStr ned_color:[UIColor ned_hint]];
            }];
            passItem.titleAtt = att;
        }];
        return;
    }
    if(IsNonNull(title)){
        [self addHeadTitleBlock:^(NEDSheetItem * _Nonnull passItem) {
            passItem.title = title;
            [passItem.titleAtt ned_color:[UIColor ned_h2]];
            [passItem.titleAtt ned_font:[UIFont ned_pfOfSize:14]];
        }];
        return;
    }
    if(IsNonNull(description)){
        [self addHeadTitleBlock:^(NEDSheetItem * _Nonnull passItem) {
            passItem.title = description;
            [passItem.titleAtt ned_color:[UIColor ned_hint]];
            [passItem.titleAtt ned_font:[UIFont ned_pfOfSize:14]];
        }];
        return;
    }
}
- (void)addHeadTitleBlock:(void (^)(NEDSheetItem * _Nonnull))callBlock{
    if(!self.titleItem){
        self.titleItem = [NEDSheetItem new];
        self.titleItem.optionType = NEDSheetOptionType_Title;
    }
    if(callBlock){
        callBlock(self.titleItem);
    }
    [self.titleItem.titleAtt ned_paragraphBlock:^(NSMutableParagraphStyle *style) {
        style.firstLineHeadIndent = Adapted(20);
        style.headIndent= Adapted(20);
        style.tailIndent = Adapted(-20);
        style.alignment = NSTextAlignmentCenter;
        style.lineBreakMode = NSLineBreakByCharWrapping;
    }];
}

@end





